package club.kynb.mall.application.limiter;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@AllArgsConstructor
public class RedisSmsSendRateLimiter implements RateLimiter {
    private static final String SMS_SEND_RATE_LIMITER = "SmsSendRateLimiter";
    private final RedissonClient redissonClient;

    @Override
    public boolean isExceedRate(String key) {
        String limitKey = getKey(key);
        RLock lock = redissonClient.getLock(limitKey);
        return lock.isLocked();
    }

    @Override
    public void limitRate(String key, long timeout, TimeUnit timeUnit) {
        String limitKey = getKey(key);
        RLock lock = redissonClient.getLock(limitKey);
        try {
            lock.tryLock(0, timeout, timeUnit);
        } catch (InterruptedException e) {
        }
    }

    @Override
    public void clean(String key) {
        String limitKey = getKey(key);
        RLock lock = redissonClient.getLock(limitKey);
        if (lock.isLocked()) {
            lock.unlock();
        }
    }

    private String getKey(String key) {
        return String.format("%s:%s", SMS_SEND_RATE_LIMITER, key);
    }
}
